//
//  MechanismListViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/21.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "MechanismListViewModel.h"

#import "MechanismInfosData.h"

@interface MechanismListViewModel()

@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;

@property (nonatomic, readwrite, strong) RACCommand* selectCmd;
@property (nonatomic, readwrite, strong) RACCommand* showDetailCmd;

@property (nonatomic, strong) ProvinceListData* zoneData;

@property (nonatomic, copy) NSString* zone;

@end

@implementation MechanismListViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.cellHeight = 94.0f;
    
    self.lastPage = 100;
    self.shouldMultiSections = NO;
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = YES;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    
    /// 选中
    //    self.selectCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(ArticleItemViewModel * itemViewModel) {
    //        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    //            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0), dispatch_get_main_queue(), ^{
    //                [subscriber sendNext:itemViewModel];
    //                [subscriber sendCompleted];
    //            });
    //            return nil;
    //        }];
    //    }];
    /// 允许并行执行
    self.selectCmd.allowsConcurrentExecution = NO;
    
    
    self.showDetailCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                          {
                              @strongify(self);
                              
                              NSIndexPath* indexPath = input;
                              
                              MechanismListCellModel* curCellModel = self.dataSource[indexPath.row];
                              MechanismInfoData* infoData = curCellModel.data;
                              
                              return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                              {
                                  [subscriber sendNext:infoData.userID];
                                  [subscriber sendCompleted];
                                  
                                  return nil;
                              }];
                          }];
    
    DataManager* dm = [DataManager sharedDataManager];
    self.zoneData = dm.locationPLData;
    
    RACSignal* zoneChangeSignal = [RACObserve(self, zoneData) distinctUntilChanged];
    [[zoneChangeSignal replay] subscribeNext:^(id x)
     {
         @strongify(self);
         
         ProvinceListData* curPListData = x;
         
         if (x == nil)
         {
             self.zone = @"全国";
         }
         else
         {
             self.zone = curPListData.name;
         }
         
         self.lastPage = 999;
         
         [self.requestRemoteDataCommand execute:@0];
     }];
    
    RAC(self, categoryTitle) = [[RACObserve(self, category) distinctUntilChanged] map:^id(id value)
    {
        NSNumber* num = value;
        
        NSInteger categoryTag = [num integerValue];
        
        NSString* strResult = @"";
        switch (categoryTag)
        {
            case 1:
            {
                strResult = @"监测单位";
            }
                break;
                
            case 2:
            {
                strResult = @"污染治理单位";
            }
                break;
                
            case 3:
            {
                strResult = @"危废处理单位";
            }
                break;
                
            case 4:
            {
                strResult = @"环保服务单位";
            }
                break;
                
            default:
                break;
        }
        
        return strResult;
    }];
}

- (void)resetZoneData:(ProvinceListData*)zoneData
{
    self.zoneData = zoneData;
}

- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        @strongify(self);
        
        NSString* strAreaID = self.zoneData ? self.zoneData.areaID : @"0";
        
        @weakify(self);
        return [[AFNetWorkUtils racPOSTWthURL:url_interface_institution_institutionList params:interface_param_institution_institutionList(@(self.category), strAreaID, @(page+1), @(List_PageSize))] subscribeNext:^(id x)
                {
                    @strongify(self)
                    
                    /// 转化数据
                    @weakify(self);
                    
                    MechanismInfosData* infosData = [MechanismInfosData modelWithJSON:x];
                    
                    NSArray *viewModels = [infosData.datas.rac_sequence map:^MechanismListCellModel *(MechanismInfoData* data)
                                           {
                                               @strongify(self);
                                               
                                               MechanismListCellModel* cellModel = [[MechanismListCellModel alloc] initWithData:data cellHeight:self.cellHeight];
                                               
                                               return cellModel;
                                           }].array;
                    
                    if (viewModels == nil || viewModels.count < List_PageSize)
                    {
                        self.lastPage = self.page;
                        
                        if (viewModels == nil)
                            viewModels = @[];
                    }
                    else
                    {
                        self.lastPage = 999;
                    }
                    
                    if (self.shouldPullUpToLoadMore)
                    {
                        if (0 == page)
                        {
                            self.dataSource = viewModels;
                        }
                        else
                        {
                            if (self.dataSource == nil)
                            {
                                self.dataSource = viewModels;
                            }
                            else
                            {
                                self.dataSource = [self.dataSource arrayByAddingObjectsFromArray:viewModels];
                            }
                        }
                    }
                    else
                    {
                        self.dataSource = viewModels;
                    }
                    
                    if (self.lastPage == 999 && page == 0)
                    {
                        [self.refreshTriggerCommand execute:nil];
                    }
                    
                    [subscriber sendNext:nil];
                    [subscriber sendCompleted];
                }   error:^(NSError *error) {
                    //错误处理
                    
                    [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:error.userInfo[customErrorInfoKey]}]];
                    [subscriber sendCompleted];
                }
                ];
        
        return nil;
    }];
}

@end
